//导入gulp
var gulp = require('gulp');
//使用gulp-load-plugins加载插件
var gulpLoadPlugins = require('gulp-load-plugins');
var $ = gulpLoadPlugins();
//使用browersync进行浏览器同步
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
//导入webpack
var webpack = require('webpack');
//导入删除模块
var del = require('del');

gulp.task('serve', function() {
  var devConfig = require('./build/webpack.dev.conf');
  var compiler = webpack(devConfig);

  browserSync.init({
    server: './',
    open: false,
    notify: false,
    logFileChanges: false,
    port: 9000,
    middleware: [
      require('connect-history-api-fallback')(),
      require('webpack-hot-middleware')(compiler),
      require('webpack-dev-middleware')(compiler, {
        publicPath: devConfig.output.publicPath,
        stats: {
          colors: true
        }
      })
    ],
    files: ['**/*.html']
  });
});

gulp.task('serve:dist', function() {
  //run browserSync
  browserSync.init({
    server: 'dist',
    notify: false,
    logFileChanges: false,
    port: 9000
  });
});

gulp.task('webpack', ['clean'], function() {
  var proConfig = require('./build/webpack.prod.conf');
  // run webpack
  webpack(proConfig, function(err, stats) {
    if (err) throw new $.util.PluginError("webpack", err);
    $.util.log("[webpack]", stats.toString({
      colors: true
    }));
  });
});

//清理文件
gulp.task('clean', del.bind(null, ['dist']));

//默认任务
gulp.task('default', function(){
  gulp.start('webpack');
});
